// pages/publish/index.js
import {
  tosat,
  toast,
  checkPhone
} from '../../utils/util'
import base from '../../api/base'
import arealist from '../../utils/city'
const QQMapWX = require('../../utils/qqmap-wx-jssdk.js')
const app = getApp()
let qqmapsdk
Page({

  /**
   * 页面的初始数据
   */
  data: {
    entProfile: '设备介绍',
    count: 9,
    saveView: '立即发布',
    tabIndex: 0,
    tableIndex: 0,
    enterpriseIndex: 0,
    enterpriseArray: [],
    enterpriseData: [],
    productRange: '',
    code: '',
    codeArray: [],
    date: '2010-01-01',
    shortRent: '',
    longRent: '',
    compony: '',
    contact: '',
    phone: '',
    address: '',
    detailAddress: '',
    introduce: '介绍',
    idPass: true,
    companyPass: true,
    areaList: arealist,
    show: false,
    province: '', // 省
    city: '', // 市
    county: '', // 区,
    lat: 0,
    lng: 0,
    defaultPhone: '',
    defaultCompony: '',
    defaultUsername: '',
    typeDisplay: true,
    children: [],
    showList: [],
    attr: [],
    elseValue: '',
    else: false,
    attrIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.checkIndex(options)
    this.checkContent(options)
    this.initAddress()
    this.initEnterpriseArray()
    this.initPhoneAndCompony()
  },
  initPhoneAndCompony() {
    this.setData({
      defaultPhone: wx.getStorageSync('userInfo').phone,
      defaultCompony: wx.getStorageSync('userInfo').entname,
      defaultUsername: wx.getStorageSync('userInfo').username,
      phone: wx.getStorageSync('userInfo').phone,
      compony: wx.getStorageSync('userInfo').entname,
      concat: wx.getStorageSync('userInfo').username
    })
  },
  initAddress() {
    const _this = this
    const {
      lat,
      lng
    } = wx.getStorageSync('location')
    qqmapsdk = new QQMapWX({
      key: base.subkey // 必填
    })
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: lat,
        longitude: lng
      },
      success(res) {
        _this.setData({
          detailAddress: res.result.address
        })
        const params = {
          detail: {
            latitude: lat,
            longitude: lng,
            address: res.result.address
          }
        }
        _this.bindAddress(params)

      },
      fail(res) {
        // console.log(res)
        // console.log(lat, lng)
      },
      complete(res) {
        // console.log(res)
        // console.log(lat, lng)
      }
    })
  },
  initAttestation() {
    const identify = wx.getStorageSync('userInfo').ideisauth
    const entisauth = wx.getStorageSync('userInfo').entisauth
    identify === 1 ? this.setData({
      idPass: false
    }) : this.setData({
      idPass: true
    })
    entisauth === 1 ? this.setData({
      companyPass: false
    }) : this.setData({
      companyPass: true
    })
  },
  initEnterpriseArray() {
    const code = '004'
    const result = []
    app.$api.common.commonFind({
        code
      })
      .then((res) => {
        const data = res.data
        data.map((item) => {
          result.push(item.name)
        })
        this.setData({
          enterpriseArray: result,
          enterpriseData: data
        })
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  checkIndex(options) {
    console.log(options)
    options.index ? this.setData({
      tableIndex: Number(options.index),
      tabIndex: Number(options.index)
    }) : ''
  },
  checkContent(options) {
    if (!options.code) return
    this.setData({
      productRange: options.equipment,
      code: options.code
    })
    console.log(options.code)
    this.data.tabIndex === 0 ? this.initCode(options.code) : ''
  },
  initCode(code) {
    app.$api.common.commonFind({
      code
    }).then((res) => {
      const result = []
      const children = []
      const showList = []
      const attr = []
      const data = res.data
      data.map((item, index) => {
        result.push({
          name: item.name,
          code: item.code,
          // child: res.data
        })
        showList.push(false)
        attr.push({
          name: '请选择'
        })
        app.$api.common.commonFind({
          code: item.code
        }).then((res) => {
          console.log(item.code)
          children.push({
            index: index,
            data: res.data
          })
          children.sort((a, b) => {
            return a.index - b.index
          })
          this.setData({
            children
          })
        }).catch((e) => {
          tosat('请稍后再试', 1000)
        })
      })
      this.setData({
        codeArray: result,
        showList,
        attr
      })

    }).catch((e) => {
      tosat('请稍后再试', 1000)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initAttestation()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindTabChangeIndex(e) {
    const index = e.detail
    this.setData({
      tabIndex: index,
      productRange: ''
    })
  },
  bindPickerChange(e) {
    const index = e.detail.value
    this.setData({
      enterpriseIndex: index,
      typeDisplay: false
    })
  },
  bindClassify() {
    const entry = 'publish'
    const index = this.data.tabIndex
    wx.navigateTo({
      url: `../classify/index?index=${index}&entry=${entry}`,
    })
  },
  // 属性
  bindBrandChange(e) {
    const index = e.detail.value
    this.setData({
      brandIndex: index
    })
  },
  bindDateChange(e) {
    const index = e.detail.value
    this.setData({
      date: index
    })
  },
  bindTonnageChange(e) {
    const index = e.detail.value
    this.setData({
      tonnageIndex: index
    })
  },
  bindCarryChange(e) {
    const index = e.detail.value
    this.setData({
      carrayIndex: index
    })
  },
  bindCraneChange(e) {
    const index = e.detail.value
    this.setData({
      craneIndex: index
    })
  },
  bindAltitudeChange(e) {
    const index = e.detail.value
    this.setData({
      altitudeIndex: index
    })
  },
  bindPowerChange(e) {
    const index = e.detail.value
    this.setData({
      powerIndex: index
    })
  },
  bindTransportChange(e) {
    const index = e.detail.value
    this.setData({
      transportIndex: index
    })
  },
  validateCommon() {
    const index = this.data.tabIndex
    console.log(index)
    const {
      attr,
      compony
    } = this.data
    const componyname = wx.getStorageSync('userInfo').entname
    const username = wx.getStorageSync('userInfo').username
    if (this.data.productRange.trim() === '') {
      index === 0 ? toast('设备类型不能为空', 1000) : index === 1 ? toast('产品范围不能为空', 1000) : toast('维修范围不能为空', 1000)
      return false
    }
    if (index === 0) {
      const flag = attr.map((item) => {
        return item.name === '请选择'
      })
      if (flag.indexOf(true) > -1) {
        toast('设备属性不能为空', 1000)
        return false
      }
    }
    if (index !== 0) {
      if(!this.data.compony) {
        toast('公司地址不能为空', 1000)
        return false
      }
    }
    if (this.data.contact.trim() === '') {
      toast('联系人姓名不能为空', 1000)
      return false
    }
    if (!checkPhone(this.data.phone)) {
      toast('联系电话格式不正确', 1000)
      return false
    }
    if (this.data.address.trim() === '') {
      toast('地址不能为空', 1000)
      return false
    }
    if (this.data.detailAddress.trim() === '') {
      toast('详细地址不能为空', 1000)
      return false
    }
    if (!app.globalData.imgUrl.length) {
      toast('设备图片不能为空', 1000)
      return false
    }
    // if (this.data.shortRent.trim() === '') {
    //   this.setData({
    //     shortRent: '面议'
    //   })
    // }
    // if (this.data.longRent.trim() === '') {
    //   this.setData({
    //     longRent: '面议'
    //   })
    // }
    if (this.data.introduce.trim() === '') {
      toast('企业介绍不能为空', 1000)
      return false
    }
    return true
  },
  // validateRent() {

  // },
  // validateSell() {},
  // validateMaintain() {},
  handleRent(e) {
    const content = e.detail.value
    this.setData({
      shortRent: content
    })
  },
  handleLongRent(e) {
    const content = e.detail.value
    this.setData({
      longRent: content
    })
  },
  handleCompany(e) {
    const content = e.detail.value
    this.setData({
      compony: content
    })
  },
  handleContact(e) {
    const content = e.detail.value
    this.setData({
      contact: content
    })
  },
  handlePhone(e) {
    const content = e.detail.value
    this.setData({
      phone: content
    })
  },
  handleIntroduce(e) {
    const content = e.detail.value
    this.setData({
      introduce: content
    })
  },
  bindPublish(e) {
    const flag = this.validateCommon()
    if (flag) {
      const index = this.data.tabIndex
      const imgUrl = app.globalData.imgUrl
      const path = JSON.parse(app.globalData.imgUrl[0])
      console.log(path)
      const url = `${path["fileUrl"]}`
      const date = app.globalData.date
      console.log(date)
      const componyType = this.data.enterpriseArray[this.data.enterpriseIndex]
      const entType = this.data.enterpriseData[this.data.enterpriseIndex].code
      const {
        productRange,
        shortRent,
        longRent,
        compony,
        contact,
        phone,
        address,
        detailAddress,
        introduce,
        lat,
        lng,
        attr
      } = this.data
      wx.navigateTo({
        url: `../../vip/payDeatil/index?index=${index}&entType=${entType}&entScope=${productRange}&maintainScope=${productRange}&equType=${this.data.code}&equName=${productRange}&shortPrice=${shortRent}&longPrice=${longRent}&companyName=${compony}&linkName=${contact}&phone=${phone}&lon=${lng}&lat=${lat}&detailedAddress=${detailAddress}&equImgUrl=${imgUrl.join(',')}&freeDate=${date.join(',')}&url=${url}&entProfile=${introduce}&equprofile=${introduce}&equattr=${JSON.stringify(attr)}`,
      })
    } else {
      return
    }
  },
  bindAddress(params) {
    const result = []
    const _this = this
    const regArr = ['区', '县', '旗', '市', '岛', '仔']
    let address = params.detail.address
    if (address.indexOf('省') < 0) {
      const qqmapsdk = new QQMapWX({
        key: base.subkey // 必填
      })
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: params.detail.latitude,
          longitude: params.detail.longitude
        },
        success(res) {
          address = res.result.address
          const newParams = {
            detail: {
              address: res.result.address,
              latitude: params.detail.latitude,
              longitude: params.detail.longitude
            }
          }
          _this.bindAddress(newParams)
        }
      })
    } else {
      const reAddress = address.split('').reverse().join('')
      const latitude = params.detail.latitude
      const longitude = params.detail.longitude
      console.log(reAddress)
      const count = address.split('').reduce((a, v) => {
        a = v === '区' ? a + 1 : a + 0
        return a
      }, 0)
      regArr.map((item) => {
        if (item === '区' && count >= 2) {
          result.push(reAddress.lastIndexOf(item))
        } else if (reAddress.indexOf(item) > -1 && count < 2) {
          result.push(reAddress.indexOf(item))
        }
      })
      this.setData({
        detailAddress: address,
        lat: latitude,
        lng: longitude,
        address: address.substring(0, address.length - result[0])
      })
    }

  },
  bindCityConfirm(e) {
    console.log(e)
    const province = e.detail.detail.province
    const city = e.detail.detail.city
    const county = e.detail.detail.county
    const address = `${province}${city}${county}`
    this.setData({
      address,
      province,
      city,
      county,
      show: false
    })
  },
  bindCloseCity() {
    this.setData({
      show: false
    })
  },
  bindOpenCity() {
    this.setData({
      show: true
    })
  },
  bindChangeShow(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      showList
    } = this.data
    const list = showList.map((item, idx) => {
      return index === idx
    })
    this.setData({
      showList: list,
      attrIndex: index
    })
  },
  onCancel() {
    const {
      showList
    } = this.data
    const list = showList.map((item, idx) => {
      return false
    })
    this.setData({
      showList: list
    })
    console.log(this.data.showList)
  },
  onConfirm(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      name,
      code
    } = e.detail.value
    // const subIndex = e.detail.index
    const {
      showList,
      attr
    } = this.data
    attr[index] = {
      name,
      code
    }
    if (name === '其他') {
      this.setData({
        else: true
      })
    } else {
      attr[index] = {
        name,
        code
      }
    }
    const list = showList.map((item, idx) => {
      return false
    })
    this.setData({
      showList: list,
      attr
    })
  },
  bindElseConfirm(e) {
    const {
      attr,
      attrIndex
    } = this.data
    attr[attrIndex].name = this.data.elseValue
    this.setData({
      else: false,
      attr
    })
  },
  bindElseClose(e) {
    this.setData({
      else: false
    })
  },
  bindGetElseContent(e) {
    const content = e.detail.value
    this.setData({
      elseValue: content
    })
    if(this.data.elseValue.trim() === '') {
      this.setData({
        elseValue: '请选择'
      })
    }
  }
})